package com.wqy.netty;

import com.wqy.netty.codc.RequestDecoder;
import com.wqy.netty.codc.RequestEncoder;
import com.wqy.netty.codc.ResponseDecoder;
import com.wqy.netty.model.Request;
import com.wqy.netty.module.fuben.request.FightRequest;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;


import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: WangQingyang
 * @Date: 2020/3/30 13:37
 * @Description:
 */
public class Client {
    public static void main(String[] args) {
        //服务类
        ClientBootstrap clientBootstrap = new ClientBootstrap();
        //线程池
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();
        //socket工厂
        clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss,worker));
        //管道工厂
        clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                // 收到消息不用转换,直接就是字符串类型 收到和回写
                pipeline.addLast("decoder",new ResponseDecoder());
                pipeline.addLast("encoder",new RequestEncoder());
                pipeline.addLast("hiHandler", new HiHandler());
                return pipeline;
            }
        });
        //连接服务器
        ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1",10010));
        Channel channel = connect.getChannel();

        System.out.println("client start");

        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入：");
            int fubenId = Integer.parseInt(scanner.nextLine());
            int count = Integer.parseInt(scanner.nextLine());
            FightRequest fightRequest = new FightRequest();
            fightRequest.setCount(count);
            fightRequest.setFubenId(fubenId);

            Request request = new Request();
            request.setModule((short)1);
            request.setCmd((short)1);
            request.setData(fightRequest.getBytes());
            //发送
            channel.write(request);
        }
    }
}
